package com.lill.system.api;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.lill.auth2.util.OnceToken;
import com.lill.common.component.util.R;
import com.lill.system.component.SysUserServe;
import com.lill.system.constant.SystemConstant;
import com.lill.system.model.SysUserEntity;
import com.lill.system.service.ICommonRedisService;
import com.lill.system.service.ISysUserService;

@Api(value="/api/user", tags="添加意见反馈")
@RestController
public class SysUserApi {
	
	@Autowired
    private ISysUserService sysUserService;
	@Autowired
	private ICommonRedisService commonRedisService;
	@Autowired
	private SysUserServe sysUserServe;

    /**
     * 查看信息
     */
    @RequestMapping("api/user/login")
    public R info(@RequestParam String phone, @RequestParam String password, @RequestParam String domainCode) {
        SysUserEntity account = sysUserService.queryPhone(phone,domainCode);
        if(null == account){
            return  R.error("该用户不存在，请您联系管理员");
        }
        password = new Sha256Hash(password).toHex();
        if(!password.equals(account.getPassWord())){
            return  R.error("输入的密码错误，请您重新输入");
        }
        return R.ok().put("data", account);
    }
    
    @ApiOperation(value="用户登录",notes="用户登录")
    @RequestMapping(value="api/user/logon",method=RequestMethod.GET)
    public R loginInfo(@RequestParam String phone, @RequestParam String password, 
    		@RequestParam String domainCode,@RequestParam(required=false) String uniqueCode) {
    	Map<String, Object> queryParam=new HashMap<String, Object>();
    	queryParam.put("domainCode", domainCode);
    	queryParam.put("userName", phone);
    	queryParam.put("passWord", new Sha256Hash(password).toHex());
    	List<Map<String, Object>> userInfo=sysUserServe.queryUser(queryParam);
    	if(null!=userInfo&&!userInfo.isEmpty()){
    		for (Map<String, Object> map : userInfo) {
    			String userId=map.get("id").toString();
    			String token=OnceToken.createTokenWithUniqueCode(userId,uniqueCode);
    			String md5Token=DigestUtils.md5Hex(token);
    			
    			/************如果单设备登录需要在这里添加***************/
//    			String oldMd5Token=commonRedisService.getStringValueByKey(SystemConstant.APP_MD5_TOKEN+userId);
//    			if(StringUtils.isNotEmpty(oldMd5Token)){
//    				commonRedisService.delDateByKeyString(SystemConstant.APP_TOKEN+oldMd5Token);
//    			}
    			/************如果单设备登录需要在这里添加***************/
    			
    			map.put("token", token);
    			commonRedisService.setKeyStringValueMapWithTime(SystemConstant.APP_TOKEN+md5Token, map, 180, TimeUnit.DAYS);
    			map.put("token", md5Token);
    			
    			/************如果单设备登录需要在这里添加***************/
//    			commonRedisService.setKeyStringValueStringWithTime(SystemConstant.APP_MD5_TOKEN+userId, md5Token, 180, TimeUnit.DAYS);
    			/************如果单设备登录需要在这里添加***************/
			}
    		return R.ok().put("data", userInfo);
    	}else{
    		return R.failure().put("msg", "账号或密码错误，请核对");
    	}
    }

    /**
     * 查看列表
     */
    @RequestMapping("api/user/list")
    public R list(@RequestBody Map<String, Object> params) {
        List<SysUserEntity> list = sysUserService.queryAll(params);
        return R.ok().put("data", list);
    }

    /**
     * 修改登录用户密码
     */
    @RequestMapping("api/user/updPassword")
    public R password(@RequestBody Map<String,Object> mapPar) {
        String phone = mapPar.get("phone")+"";
        String code = mapPar.get("code")+"";
        String newPassword = mapPar.get("newPassword")+"";
        String confirmPassword = mapPar.get("confirmPassword")+"";
        String s = commonRedisService.getStringValueByKey(phone);
        String hcCode = commonRedisService.getStringValueByKey(phone+s)+"";
        if (code == null || "".equals(code)) {
            return R.error("请输入验证码");
        }
        if (code != null && !hcCode.equals(code)) {
            return R.error("验证码不正确");
        }
        if (newPassword ==null || "".equals(newPassword)) {
            return R.error("新密码不能为空");
        }
        if (confirmPassword ==null || "".equals(confirmPassword)) {
            return R.error("请输入确认密码");
        }
        if (!newPassword.equals(confirmPassword)) {
            return R.error("确认密码与新密码不同,请重新填写");
        }
        //sha256加密
        newPassword = new Sha256Hash(newPassword).toHex();
        Map<String,Object> map = new HashMap<>();
        map.put("userName",phone);
        List<SysUserEntity> sysUserEntities = sysUserService.queryList(map);
        if (sysUserEntities == null || sysUserEntities.size() == 0 || sysUserEntities.size() > 1 ) {
            return R.error("账号异常,请联系管理员");
        }
        SysUserEntity sysUserEntity = sysUserEntities.get(0);

        //更新密码
        int count = sysUserService.updatePassword(sysUserEntity.getId(), sysUserEntity.getPassWord(), newPassword);
        if (count == 0) {
            return R.error("原密码不正确");
        }
//         //退出
//        ShiroUtils.logout();

        return R.ok("密码修改成功");
    }


    /**
     * 修改
     */
    @RequestMapping("/api/user/update")
    public R update(@RequestBody SysUserEntity user) {
        if(user == null || user.getId() == null || StringUtils.isEmpty(user.getHeadImg())){
            return R.ok().put("mess","参数错误");
        }
        user.setUpdateUser(user.getId());
        user.setUpdateTime(new Date());
        sysUserService.updateApp(user);
        return R.ok();
    }
	
}
